﻿define([
    'Wjs/ui/widgets/fields/ToolField',
    'Wjs/ui/widgets/tools/DateSelector'
],
function () {
    'use strict';

    return Wjs.defineOnce({

        type: 'DateField',

        internal: {

            base: Wjs.getType('ToolField'),

            initialize: function () {
                var me = this;

                me.addClass('wjs-date-field');

                this.dateSelector = Wjs.new('DateSelector')

                        .onDateSelected(function (date) {

                            me.getField().setValue(date.toLocaleDateString("en-US")); // Set the date

                            this.getDatePicker().hide(); // Hide the date picker

                            if (me.dateSelectedHandler) {

                                me.dateSelectedHandler(date);
                            }
                        });

                me.setTool(this.dateSelector);
            }
        },

        getDatePicker: function() {

            return this.dateSelector.getDatePicker().getItem();
        },

        setDate: function(date) {

            this.getDatePicker().setDate(date);

            return this;
        },

        // Called when the date is set in the date picker (either a different month or year)
        onDateSet: function (fcn) {

            this.getDatePicker().onDateSet(fcn.bind(this)); // Execute it in the context of the date field

            return this;
        },

        onDaySet: function (fcn) {

            this.getDatePicker().onDaySet(fcn.bind(this)); // Execute it in the context of the date field

            return this;
        },

        onDateSelected: function (fcn) {

            this.dateSelectedHandler = Wjs.chain(this.dateSelectedHandler, fcn);

            return this;
        },

        setMinDate: function (date) {

            this.getDatePicker().setMinDate(date); 

            return this;
        },

        setMaxDate: function (date) {

            this.getDatePicker().setMaxDate(date); 

            return this;
        }

    });

});